import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/LoginTypeEnum.dart';
import 'package:tracker/pages/login/view/login_page.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/provider/global_state_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

class LoginFormModel {
  late LoginTypeEnum loginType;
  late String imei;
  late String imeiPassword;
  late String phone;
  late String phonePassword;
  late bool rememberPassword;
}

class LoginForm extends ConsumerStatefulWidget {
  LoginForm({super.key, this.callback});

  final ValueChanged<LoginFormModel>? callback;

  final loginModel = LoginFormModel();

  @override
  ConsumerState<LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends ConsumerState<LoginForm> {
  final _textNormalFontSize = 15.0;
  final _textSelectedFontSize = 17.0;

  final _imeiController = TextEditingController();
  final _imeiPasswordController = TextEditingController();

  final _phoneController = TextEditingController();
  final _phonePasswordController = TextEditingController();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
    super.initState();
  }

  _afterLayout(_) {
    // 测试设备号登录
    ref.read(globalStateProvider.notifier).updateLoginType(LoginTypeEnum.device);
    // _imeiController.text = "58053177512";
    // _imeiPasswordController.text = "123456";
    // 是否记住了密码（rememberPasswordModel仅支持记住设备登录、手机号登录的密码）
    final rememberPasswordModel = SpUtil.getObj('rememberPasswordModel', (v) => RememberPasswordModel().fromJson(v),
        defValue: RememberPasswordModel(rememberPassword: false)) as RememberPasswordModel;
    if (rememberPasswordModel.rememberPassword!) {
      if (rememberPasswordModel.loginType == '4') {
        _imeiController.text = rememberPasswordModel.username!;
        _imeiPasswordController.text = rememberPasswordModel.password!;
      } else {
        _phoneController.text = rememberPasswordModel.username!;
        _phonePasswordController.text = rememberPasswordModel.password!;
      }
    }
  }

  /// 构建设备登录方式文本
  AnimatedDefaultTextStyle _buildText(String text, LoginTypeEnum type) {
    final loginType = ref.watch(globalStateProvider).loginType;
    return AnimatedDefaultTextStyle(
        style: loginType == type
            ? TextStyle(
                fontSize: _textSelectedFontSize, color: AppTheme.themeConfig.primaryColor, fontWeight: FontWeight.w900)
            : TextStyle(fontSize: _textNormalFontSize, color: Colors.white),
        duration: const Duration(milliseconds: 100),
        child: Text(text));
  }

  /// 构建登录表单输入框
  List<Widget> _buildLoginFormTextFields() {
    final loginType = ref.watch(globalStateProvider).loginType;
    final textColor = Colors.white;
    return loginType == LoginTypeEnum.device
        ? [
            // 设备号登录
            TextField(
              controller: _imeiController,
              onChanged: (str) {},
              style: TextStyle(color: textColor),
              decoration: InputDecoration(
                hintText: "请输入设备号",
                hintStyle: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
                // 调整内边距
                contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                    width: 2,
                  ),
                ),
                filled: true,
                fillColor: Colors.white.withOpacity(0.15),
              ),
            ),
            const SizedBox(
              height: 12,
            ),
            TextField(
              controller: _imeiPasswordController,
              obscureText: true,
              style: TextStyle(color: textColor),
              decoration: InputDecoration(
                hintText: "请输入密码",
                hintStyle: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
                // 调整内边距
                contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                    width: 2,
                  ),
                ),
                filled: true,
                fillColor: Colors.white.withOpacity(0.15),
              ),
            ),
          ]
        : [
            // 手机号登录
            TextField(
              controller: _phoneController,
              style: TextStyle(color: textColor),
              decoration: InputDecoration(
                hintText: "请输入手机号",
                hintStyle: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
                // 调整内边距
                contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                    width: 2,
                  ),
                ),
                filled: true,
                fillColor: Colors.white.withOpacity(0.15),
              ),
            ),
            const SizedBox(
              height: 12,
            ),
            TextField(
              controller: _phonePasswordController,
              style: TextStyle(color: textColor),
              obscureText: true,
              decoration: InputDecoration(
                hintText: "请输入密码",
                hintStyle: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
                // 调整内边距
                contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                    width: 2,
                  ),
                ),
                filled: true,
                fillColor: Colors.white.withOpacity(0.15),
              ),
            ),
          ];
  }

  /// 登录按钮点击事件
  _onLoginBtnClick() {
    final loginType = ref.watch(globalStateProvider).loginType;
    final rememberPassword = ref.watch(rememberPasswordProvider);
    if (loginType == LoginTypeEnum.device) {
      // 设备号登录
      final imei = _imeiController.text;
      final imeiPassword = _imeiPasswordController.text;
      if (imei.isEmpty) {
        ToastUtils.showToast("请输入设备号");
        return;
      }
      if (imeiPassword.isEmpty) {
        ToastUtils.showToast("请输入密码");
        return;
      }
      widget.loginModel.loginType = LoginTypeEnum.device;
      widget.loginModel.imei = imei;
      widget.loginModel.imeiPassword = imeiPassword;
    } else {
      // 手机号登录
      final phone = _phoneController.text;
      final phonePassword = _phonePasswordController.text;
      if (phone.isEmpty) {
        ToastUtils.showToast("请输入手机号");
        return;
      }
      if (phonePassword.isEmpty) {
        ToastUtils.showToast("请输入密码");
        return;
      }
      widget.loginModel.loginType = LoginTypeEnum.phone;
      widget.loginModel.phone = phone;
      widget.loginModel.phonePassword = phonePassword;
    }
    widget.loginModel.rememberPassword = rememberPassword;
    widget.callback?.call(widget.loginModel);
  }

  @override
  Widget build(BuildContext context) {
    // 屏幕高
    double screenHeight = ScreenUtil.getInstance().screenHeight;
    double offset = screenHeight / 4 - 120;

    return Container(
      padding: const EdgeInsets.only(left: 20, right: 20),
      child: Transform.translate(
        // offset: Offset(0, offset),
        offset: Offset(0, 0),
        child: Column(
          // mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              height: 60,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.baseline,
                  textBaseline: TextBaseline.alphabetic,
                  children: [
                    GestureDetector(
                        onTap: () {
                          ref.read(globalStateProvider.notifier).updateLoginType(LoginTypeEnum.device);
                        },
                        child: _buildText("设备号登录", LoginTypeEnum.device)),
                    const SizedBox(width: 24),
                    GestureDetector(
                      onTap: () {
                        ref.read(globalStateProvider.notifier).updateLoginType(LoginTypeEnum.phone);
                      },
                      child: _buildText("手机号登录", LoginTypeEnum.phone),
                    )
                  ]),
            ),
            // 输入框
            ..._buildLoginFormTextFields(),
            // 记住密码
            Row(
              children: [
                Checkbox(
                  value: ref.watch(rememberPasswordProvider),
                  onChanged: (value) {
                    ref.read(rememberPasswordProvider.notifier).state = value!;
                  },
                  // 选中的颜色
                  activeColor: AppTheme.themeConfig.primaryColor,
                ),
                const Text(
                  "记住密码",
                  style: TextStyle(color: Colors.white),
                ),
                const Spacer(),
                if (ref.watch(globalStateProvider).loginType == LoginTypeEnum.phone)
                  TextButton(
                    onPressed: () {
                      context.push(RouterManager.forgotPassword);
                    },
                    child: const Text(
                      "忘记密码?",
                      style: TextStyle(color: Colors.white),
                    ),
                  )
              ],
            ),
            // 登录按钮
            SizedBox(
              width: double.infinity,
              height: 52,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [
                      AppTheme.themeConfig.primaryColor,
                      AppTheme.themeConfig.primaryColor.withOpacity(0.85),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(26),
                  boxShadow: [
                    BoxShadow(
                      color: AppTheme.themeConfig.primaryColor.withOpacity(0.3),
                      blurRadius: 12,
                      offset: const Offset(0, 6),
                    ),
                  ],
                ),
                child: ElevatedButton(
                  onPressed: () {
                    _onLoginBtnClick();
                    // 测试绑定手机号
                    // context.pushNamed('bind-phone');
                  },
                  style: ButtonStyle(
                    shape: MaterialStateProperty.all(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(26),
                      ),
                    ),
                    backgroundColor: MaterialStateProperty.all(Colors.transparent),
                    elevation: MaterialStateProperty.all(0),
                    shadowColor: MaterialStateProperty.all(Colors.transparent),
                  ),
                  child: const Text(
                    "登录",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 17,
                      fontWeight: FontWeight.w700,
                      letterSpacing: 1.2,
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: offset,
            )
          ],
        ),
      ),
    );
  }
}
